import re
import json
from requests_toolbelt import MultipartEncoder
from frame_work.type_file import (
    TfxSource
)
from frame_work.release_util import tfx_release
from frame_work.logger import Logger
from frame_work.tfx_util import (
    change_user_account_status,
    get_binded_shop_list,
    bind_shop,
    get_seller_level,
    get_order_url,
    assert_result_dict
)
from frame_work.login import PcLogin
from frame_work import menu_list
from workspace.shikee.chuji.pay import PayQuantity
from frame_work.yaml_file import YAML
from frame_work.setting import *

logger = Logger(__name__).get_logger()


class Activity(object):

    def __init__(self, uname):
        self.uname = uname
        # self.logger = Logger(logger="release").get_logger()
        self.session = self.get_session()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_session(self):
        """
        :return:返回登录session
        """
        login = PcLogin(self.uname)
        login.tfx_pc_login()
        return login.get_session()

    def get_html(self):
        """
        请求一个页面，在响应中获取比如：token，shopId等
        :return: html
        """
        url = self.yaml.get_data("tfx_token").get('url')
        html = self.session.get(url, headers=self.yaml.get_data(
            "tfx_token")['header'], allow_redirects=False).text
        return html

    def get_token(self):
        """
        从html中通过正则表达式获取token
        :return:token
        """
        complex_value = 'name="token" value="(.*?)"'
        html = self.get_html()
        token = re.findall(complex_value, html)
        try:
            token = token[0]
            logger.debug('获取token值 => %s ...' % token)
        except (IndexError, KeyError) as e:
            logger.debug("获取token出错")
            return False
        else:
            return token

    @staticmethod
    def get_title(source, plan='按时段'):
        """
        通过活动类型和来源的拼接，返回对应的title
        :param source:来源
        :return:title
        """
        title = ''
        # 商品来源为淘宝
        if source == '淘宝':
            title = '淘宝_' + plan + '_刘'
        # 商品来源为天猫
        elif source == '天猫':
            title = '天猫_' + plan + '_刘'
        # 商品来源为京东
        elif source == '京东':
            title = '京东_' + plan + '_刘'
        # 商品来源为拼多多
        elif source == '拼多多':
            title = '拼多多_' + plan + '_刘'
        logger.debug('根据来源获取title值 => %s ...' % title)
        return title

    @staticmethod
    def get_image(title):
        """
        通过title来判断/image下取哪个image图片，主要用于get_pic函数中用于post
        :param title:
        :return:
        """
        title = title[:-2]
        for image in os.listdir(image_Path):
            if title + '.jpg' == image:
                return image

    def get_pic(self, num, title, is_json=False):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取响应值类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :param title:活动类型与来源的拼接
        :return:pic_addr
        """
        shikee_cookies = self.session.cookies.get(
            'taotaofa')  # 获取用户cookies中的shikee部分
        yaml_data = self.yaml.get_data("tfx_tmp_pic_address")
        yaml_data.get('data').update({
            'name': Activity.get_image(title),  # num:发布活动页面有多个上传图片地方,用于区别
            'Filedata': ('filename', open(os.path.join(image_Path, Activity.get_image(title)), 'rb'), 'image/jpg')
        })
        url = yaml_data.get('url') + '/' + str(num) + \
            '?swf_upload_cookie=' + shikee_cookies
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = self.session.post(url, data=m,
                              headers={'Content-Type': m.content_type})
        if is_json:
            return json.loads(r.text)
        return r.text

    def get_distributed_plan(self, type):
        plan_type = ''
        if type == '1':
            plan_type = '分时段'
        elif type == '2':
            plan_type = '按天'
        elif type == '3':
            plan_type = '统一'
        return plan_type

    def release_basic(self, *args, **kwargs):
        """
        发布封装
        :param args:
        :param kwargs:
        :return:
        """
        source = kwargs.get("source")
        section_radio = kwargs.get("plan_type")
        value = get_seller_level(self.uname)
        level = value[0].get("level")
        shop_id = ''
        if level != 0:
            value = get_binded_shop_list(self.uname, TfxSource[source].value)
            if not value:
                bind_shop(source, self.uname)
                value = get_binded_shop_list(
                    self.uname, TfxSource[source].value)
            shop_id = value[0].get("id")
        cn_plan_type = self.get_distributed_plan(section_radio)
        title = Activity.get_title(source, cn_plan_type)
        title_pic = self.get_pic(2, title, True).get('data')
        search_pic = self.get_pic(2, '淘发现手淘搜索图_刘', True).get('data')
        img_detail_pic = self.get_pic(2, title, True).get('data')
        url, post_data, header = tfx_release(
            source=TfxSource[source].value, shopId=shop_id,
            shop_name=source + "的店铺", url_order=get_order_url(source),
            Title=title,
            img_list=title_pic, section_radio=int(section_radio),
            search_pic=search_pic, img_detail_pic=img_detail_pic,
            token=self.get_token()
        )
        logger.debug('开始发布' + title)
        response = self.session.post(url, data=post_data, headers=header).text
        cn_level = '单期商家' if level == 0 else 'vip商家'
        status = assert_result_dict(
            response, cn_level + self.uname + '发布' + title)
        self.pay(status, response)

    def release_activity(self, source, plan_type):
        """
        发布普通活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, plan_type=plan_type)

    def pay(self, status, response):
        if status:
            tid = json.loads(response).get("data").split('/')[-1]
            logger.info("该活动tid为：%s" % tid)
            logger.info("即将执行支付活动担保金操作...  请稍等....")
            pay = PayQuantity(self.session)
            pay.test_pay_quantity(tid, 'taotaofa')


def main():
    while True:
        # 选择功能菜单
        menu_list.tfx_release_menu()
        # 选择
        source = input("请选择活动来源: ")
        if source in ('q', 'Q'):
            break
        # 选择功能菜单
        menu_list.tfx_release_plan()
        # 选择
        plan_type = input("请选择活动计划: ")
        if plan_type in ('q', 'Q'):
            break
        # seller_uname = input(u'请输入商家用户名: ')
        seller_uname = input(u'请输入商家用户名: ')
        status = change_user_account_status(seller_uname)
        if not status:
            break
        source = TfxSource(int(source)).name
        activity = Activity(seller_uname)
        activity.release_activity(source, plan_type)


if __name__ == "__main__":
    main()
